package com.xiaohe66.web.domain.sys.sec.service;

import com.xiaohe66.common.util.RsaUtils;
import com.xiaohe66.web.domain.sys.sec.repository.SysConfigRepository;
import com.xiaohe66.web.domain.sys.sec.value.SysSecretKey;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Service;

/**
 * @author xiaohe
 * @since 2023-12-27 17:41
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SysConfigService implements ApplicationRunner, Ordered {

    private final SysConfigRepository sysConfigRepository;

    @Override
    public void run(ApplicationArguments args) {

        SysSecretKey sysSecretKey = sysConfigRepository.getSysSecretKey();

        if (sysSecretKey == null) {

            log.info("sysSecretKey is null, init start");

            RsaUtils.RsaKey rsaKey = RsaUtils.createKey();

            sysSecretKey = new SysSecretKey(rsaKey.getPrivateKey(), rsaKey.getPublicKey());

            sysConfigRepository.saveSysSecretKey(sysSecretKey);

            log.info("sysSecretKey is null, init end");
        }
    }

    @Override
    public int getOrder() {
        // 需要保证初始化方法 在其他需要使用密钥的方法前执行
        return 0;
    }
}
